import { io } from "socket.io-client";

export class NetworkManager {
  constructor(onGameStart, onMoveMade, onPlayerLeft) {
    this.socket = io("http://30.165.41.10:4399/");
    this.roomId = null;
    this.playerId = null;

    this.socket.on("roomCreated", ({ roomId, playerId }) => {
      this.roomId = roomId;
      this.playerId = playerId;
      console.log(`创建房间成功: 房间id:${roomId} 玩家id:${playerId}`);
    });

    this.socket.on("gameJoined", ({ roomId, playerId }) => {
      this.roomId = roomId;
      this.playerId = playerId;
      console.log(`加入房间成功: 房间id:${roomId} 玩家id:${playerId}`);
    });

    this.socket.on("gameStart", onGameStart);
    this.socket.on("moveMade", onMoveMade);
    this.socket.on("playerLeft", onPlayerLeft);
    this.socket.on("error", (message) => {
      console.error("Game error:", message);
      alert(message);
    });
  }

  createRoom() {
    this.socket.emit("createRoom");
  }

  joinRoom(roomId) {
    this.socket.emit("joinRoom", roomId);
  }

  makeMove(row, col) {
    if (this.roomId) {
      this.socket.emit("move", { roomId: this.roomId, row, col });
    }
  }
}
